package com.yayawan.laomigame;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.webkit.WebSettings;
import android.widget.Button;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;


import com.jiafan.dy.R;
import com.yayawan.laomigame.callback.LaomiGameApi;
import com.yayawan.utils.DeviceUtil;
import com.yayawan.utils.Yayalog;
import com.ycbjie.webviewlib.inter.InterWebListener;
import com.ycbjie.webviewlib.utils.X5WebUtils;
import com.ycbjie.webviewlib.view.X5WebView;
import com.ycbjie.webviewlib.widget.WebProgress;

import java.util.List;

/**
 * <pre>
 *     @author yangchong
 *     blog  : https://github.com/yangchong211
 *     time  : 2019/9/17
 *     desc  : webView页面
 *     revise: 暂时先用假数据替代
 * </pre>
 */
public class AdvancedWebViewActivity extends AppCompatActivity {

    private X5WebView mWebView;
    private WebProgress progress;
    private String url;

    private static Activity mActivity;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() ==
                KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (mWebView!=null){
                mWebView.loadUrl("javascript:LaomiGameCallBack.onKeyDownPre()");
            }
            return true;
        }else {
            return super.onKeyDown(keyCode, event);
        }

    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.destroy();
            //mWebView = null;
        }
        super.onDestroy();
    }


    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void onResume() {
        super.onResume();
        if (mWebView != null) {
            mWebView.onResume();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mWebView != null) {
            mWebView.getSettings().setJavaScriptEnabled(false);
        }
    }
    LaomiGameApi mlaomigameapi;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        mActivity=this;

        Button viewById = findViewById(R.id.bt_gotodownload);
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //String gameid, String gamename,String gameurl,String gameiconurl
                //mlaomigameapi.addDownloadTask("1524","王者修仙","http://d.apps.yayawan.com/apk/yjxxwzxxyyw/0610yjxx001.apk","https://att.yayawan.com/upload/2019/12/05/f3c1eb17eb.png?imageView2/1/w/250/h/250");
            }
        });
        Button bt_gotodownload2 = findViewById(R.id.bt_gotodownload2);
        bt_gotodownload2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //String gameid, String gamename,String gameurl,String gameiconurl
              //  mlaomigameapi.addDownloadTask("1525","三国塔防","http://d.apps.yayawan.com/apk/tfsgztf/0729dfsgc001.apk","https://att.yayawan.com/upload/2020/06/16/0809232527.png?imageView2/1/w/250/h/250");
            }
        });
        getOaid();
        initData();
        initView();

        //获取oaid保存在appcation中



    }


    public void initData() {
        Intent intent = getIntent();
        if (intent!=null){
            url = intent.getStringExtra("url");
        }
    }

    public void initView() {
        mWebView = findViewById(R.id.web_view);

        mlaomigameapi=  new LaomiGameApi(mActivity,mWebView);
        progress = findViewById(R.id.progress);
        //progress.show();
      //  progress.setColor(this.getResources().getColor(R.color.colorAccent),this.getResources().getColor(R.color.colorPrimaryDark));

       // mWebView.loadUrl("http://api.hengxianggame.net/wan/index/?appid=2159465564");
       // mWebView.loadUrl("http://tl.3469.net:7903/");
       String appid= DeviceUtil.getGameInfo(mActivity,"qianguo_app_id").replace("kk","");
       mWebView.loadUrl("https://gm.kingoo.com.cn/#/?app_id="+appid+"&kk="+System.currentTimeMillis());

      //  mWebView.loadUrl("http://tl.3469.net:7903/");

        //Log.d()
        //mlaomigameapi
        // 设置与Js交互的权限
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        // 设置允许JS弹窗
       // mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.addJavascriptInterface(mlaomigameapi, "LaomiGameApi");//AndroidtoJS类对象映射到js的test对象
       // mWebView.loadUrl("file:///android_asset/test.html");
       // mWebView.setWebChromeClient(new X5WebChromeClientNew(mWebView,this));
        mWebView.getX5WebChromeClient().setWebListener(interWebListener);
        mWebView.getX5WebViewClient().setWebListener(interWebListener);
        mWebView.getX5WebChromeClient().setShowCustomVideo(false);
        //setShowCustomVideo
       mWebView.setInitialScale(1000);

    }


    private InterWebListener interWebListener = new InterWebListener() {
        @Override
        public void hindProgressBar() {
         //   progress.hide();
        }

        @Override
        public void showErrorView(@X5WebUtils.ErrorType int type) {
            switch (type){
                //没有网络
                case X5WebUtils.ErrorMode.NO_NET:
                    break;
                //404，网页无法打开
                case X5WebUtils.ErrorMode.STATE_404:

                    break;
                //onReceivedError，请求网络出现error
                case X5WebUtils.ErrorMode.RECEIVED_ERROR:

                    break;
                //在加载资源时通知主机应用程序发生SSL错误
                case X5WebUtils.ErrorMode.SSL_ERROR:

                    break;
                default:
                    break;
            }
        }

        @Override
        public void startProgress(int newProgress) {
           // progress.setWebProgress(newProgress);
        }

        @Override
        public void showTitle(String title) {

        }


    };


    public class AndroidBug5497Workaround {

        // For more information, see https://code.google.com/p/android/issues/detail?id=5497
        // To use this class, simply invoke assistActivity() on an Activity that already has its content


        public void assistActivity (Activity activity) {
            new AndroidBug5497Workaround(activity);
        }
        private Activity activity;
        private View mChildOfContent;
        private int usableHeightPrevious;
        private FrameLayout.LayoutParams frameLayoutParams;

        private AndroidBug5497Workaround(Activity activity) {
            this.activity = activity;
            FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
            mChildOfContent = content.getChildAt(0);
            mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    possiblyResizeChildOfContent();
                }
            });
            frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
        }

        private void possiblyResizeChildOfContent() {
            int usableHeightNow = computeUsableHeight();
            //LogUtils.e("possiblyResizeChildOfContent","usableHeightNow:"+usableHeightNow);
            //LogUtils.e("possiblyResizeChildOfContent","usableHeightPrevious:"+usableHeightPrevious);
            if (usableHeightNow != usableHeightPrevious) {
                int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();

                //这个判断是为了解决19之前的版本不支持沉浸式状态栏导致布局显示不完全的问题
                if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT){
                    Rect frame = new Rect();
                    activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
                    int statusBarHeight = frame.top;
                    usableHeightSansKeyboard -= statusBarHeight;
                }
                int heightDifference = usableHeightSansKeyboard - usableHeightNow;
                if (heightDifference > (usableHeightSansKeyboard/4)) {
                    // keyboard probably just became visible
                    frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
                } else {
                    // keyboard probably just became hidden
                    frameLayoutParams.height = usableHeightSansKeyboard;
                }
                mChildOfContent.requestLayout();
                usableHeightPrevious = usableHeightNow;
            }
        }

        private int computeUsableHeight() {
            Rect frame = new Rect();
            activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
            int statusBarHeight = frame.top;
            Rect r = new Rect();
            mChildOfContent.getWindowVisibleDisplayFrame(r);
            //这个判断是为了解决19之后的版本在弹出软键盘时，键盘和推上去的布局（adjustResize）之间有黑色区域
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                return (r.bottom - r.top)+statusBarHeight;
            }
            return (r.bottom - r.top);
        }

    }





    private static MiitHelper miitHelper;

    public static void getOaid() {
        // Inflate the menu; this adds items to the action bar if it is present.

        try {

            if (Build.VERSION.SDK_INT >= 28) {

                miitHelper = new MiitHelper(new MiitHelper.AppIdsUpdater() {

                    @Override
                    public void OnIdsAvalid(final String ids) {
                        // TODO Auto-generated method stub
                        App.oaid = ids;
                      //  Toast.makeText(mActivity, "Handle.active_handler======================"+ids, Toast.LENGTH_SHORT).show();


                    }
                });

                miitHelper.getDeviceIds(mActivity);

            }

        } catch (Exception e) {
            // TODO: handle exception
            Yayalog.loger("当前sdk 获取oaid id 异常：");
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

        }
    }
}
